<template>
  <div style="display: flex;margin: 20px 10px;gap: 20px">
    <div style="flex: 1">
      <light-card>
        <div class="create-topic" @click="edit = true">
          <el-icon><EditPen /></el-icon>
          点击发表主题...
        </div>
        <div style=" margin-top: 10px; display: flex; gap: 13px; font-size: 18px; color: grey">
          <el-icon><Edit /></el-icon>
          <el-icon><Document /></el-icon>
          <el-icon><Compass /></el-icon>
          <el-icon><Picture /></el-icon>
          <el-icon><Microphone /></el-icon>
        </div>
      </light-card>

      <light-card style="display: flex;gap: 10px;flex-direction: column;margin-top: 10px" v-if="top.length">
        <div v-for="to in top" style="display: flex" class="top-card" @click="router.push('/index/topic-detail/'+to.id)" >
          <el-tag style="margin-left: 10px" size="small" type="primary"  >置顶</el-tag>
          <div >{{to.title}}</div>
          <div>{{new Date(to.time).toLocaleString()}}</div>
        </div>
      </light-card>
      <light-card style="margin-top: 10px;display: flex;gap: 10px">
        <div
          :class="`type-select-card ${type === item.id ? 'active': ''}`"
          v-for="item in store.state.forum.types"
          :key="item.id"
          @click="handleTypeChange(item.id)"
        >
          <ColorDot :color="item.color"></ColorDot>
          <span style="margin-left: 5px">{{ item.name }}</span>
        </div>
      </light-card>
      <div style="margin-top: 10px;display: flex;flex-direction: column">
        <transition name="fade-scale" mode="in-out">
          <div v-if="list.length" key="topic-list" v-infinite-scroll="getTopics">
            <light-card
                @click = "router.push('/index/topic-detail/'+item.id)"
              style="margin-top: 10px;"
              v-for="item in list"
              class="topic-card"
            >
              <div style="display: flex;gap: 10px">
                <div>
                  <el-avatar size="default" :src="avatarGet(item.avatar)"></el-avatar>
                </div>
                <div>
                  <div style="font-size: 15px;font-weight: bold"> {{ item.username }}</div>
                  <div style="font-size: 12px;color: grey">
                    <el-icon><Timer></Timer></el-icon>
                    <div style="margin-left: 2px;display:inline-block;transform: translateY(-1px)">{{ new Date(item.time).toLocaleString() }}</div>
                  </div>
                </div>
              </div>
              <div style="margin-top: 2px">
<TopicTag :type="item.type"></TopicTag>
                <span style="font-weight: bold">{{ item.title }}</span>
              </div>
              <div class="topic-content">
                {{ item.text }}
              </div>
              <div style="display: grid;grid-template-columns: repeat(3,1fr);grid-gap: 10px">
                <el-image class="image-class" v-for="img in item.images" :src="img" fit="cover" :key="img"></el-image>
              </div>
              <div class="action-container">
                <div class="action-item">
                  <el-icon class="icon"><CircleCheck /></el-icon> {{ item.like }} 点赞
                </div>
                <div class="action-item">
                  <el-icon class="icon"><Star /></el-icon> {{ item.collect }} 收藏
                </div>
              </div>
            </light-card>
          </div>
        </transition>
      </div>
    </div>
    <div style="width: 350px;margin-right: 15px">
      <div style="position: sticky;top: 20px;">
        <light-card>
          <div class="list-collect-button" @click="collect = true">
            <span><el-icon><FolderOpened></FolderOpened></el-icon>查看我的收藏</span>
            <el-icon style="transform: translateY(3px)"><ArrowRightBold></ArrowRightBold></el-icon>
          </div>
        </light-card>
        <light-card style="font-weight: bold;margin-top: 10px">
          <el-icon style="translate: 0 2px"><CollectionTag /></el-icon>
          论坛公告
          <el-divider style="margin: 10px 0"></el-divider>
          <div style="font-size: 14px;color: grey;margin-top: 10px">
            各位论坛用户：<br/>
            为优化交流环境，近期将对板块进行整合调整，部分功能也会升级优化。在此期间，可能出现短暂访问异常，我们会全力缩短时长并及时通报进展。感谢您的理解与支持，让我们携手共创更优质的论坛空间。
          </div>
        </light-card>
        <light-card style="margin-top: 15px">
          <div style="font-weight: bold">
            <el-icon><Calendar /></el-icon>
            天气信息
            <el-divider style="margin: 10px 0"></el-divider>
          </div>
          <weather :data="weather"></weather>
        </light-card>
        <light-card style="margin-top: 15px">
          <div class="info">
            <div>当前日期</div>
            <div>{{ today }}</div>
          </div>
          <div class="info">
            <div>当前ip地址</div>
            <div>127.0.0.1</div>
          </div>
        </light-card>
        <div style="margin: 10px 0;color: gray">
          <el-icon><Link /></el-icon>
          友情链接
          <el-divider style="margin-top: 10px"></el-divider>
          <div style="display: grid;grid-template-columns: repeat(2,1fr);grid-gap: 10px">
            <div class="friend-link">
              <el-image src="https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"></el-image>
            </div>
            <div class="friend-link">
              <el-image src="https://img.88icon.com/download/jpg/20201129/5cf166ba605929a8cd6d8614f7822973_512_512.jpg!bg"></el-image>
            </div>
          </div>
        </div>
      </div>
    </div>
    <TopicCollectList :show="collect" @close="collect = false"></TopicCollectList>

    <TopicEditor :show="edit" @success="handleSuccess()" @close="edit = false"></TopicEditor>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onBeforeMount, watch } from "vue";
import { get } from "@/net/index.js";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import LightCard from "@/componments/light-card.vue";
import Weather from "@/componments/Weather.vue";
import TopicEditor from "@/componments/TopicEditor.vue";
import {
  Calendar,
  CollectionTag,
  Compass,
  Document,
  Edit,
  EditPen,
  Link,
  Picture,
  Microphone,
  Timer, CircleCheck, Star, FolderOpened, ArrowRightBold
} from "@element-plus/icons-vue";
import axios from "axios";
import ColorDot from "@/componments/ColorDot.vue";
import router from "@/router/main.js";
import TopicTag from "@/components/views/forum/TopicTag.vue";
import TopicCollectList from "@/componments/TopicCollectList.vue";

const today = ref('');
const weather = reactive({
  location: '',
  now: "",
  hourly: "",
  success: false,
});

const type = ref(0)
const edit = ref(false);
const list = ref([]);
const store = useStore();
let top = ref([]);
let end = ref(false)
const collect = ref(false)
 function avatarGet(avatar){
  if(avatar)
    return `${axios.defaults.baseURL}/images/${avatar}`
  return "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
}

onMounted(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  today.value = `${year}-${month}-${day}`;
  get("api/forum/top-topic", data => {
    top.value = data;
  })
  getTopics();
  navigator.geolocation.getCurrentPosition(function (position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;
    get(`api/forum/weather?latitude=${latitude}&longitude=${longitude}`, data => {
      ElMessage.success("已同步天气数据");
      Object.assign(weather, data);
      weather.success = true;
    }, error => {
      console.log(error);
      ElMessage.error("获取天气数据失败,请检查网络设置");
      get("api/forum/weather?latitude=39.90499&longitude=116.40529", data => {
        Object.assign(weather, data);
        weather.success = true;
      });
    }, {
      timeout: 5000,
      enableHighAccuracy: true
    });
  });

});
let page = 0
function handleSuccess() {
  list.value = [];
  edit.value = false;
  page = 0;
  type.value = 0;
  end.value= false; // 先设置 end 为 false
  console.log(end.value)
  getTopics(); // 再调用 getTopics
}

function getTopics() {
  console.log("我被调用了")
  if (end.value) return;
  get(`api/forum/list-topic?page=${page}&type=${type.value}`, data => {
    const topics = Array.isArray(data) ? data : [];
    if (topics.length > 0) {
      console.log("我进来了")
      topics.forEach(item => list.value.push(item));
      page+=1;

    } else {
      end.value = true;
    }
  });
}

function handleTypeChange(newType) {
  type.value = newType;
  list.value = [];
  page=  0;
  end.value = 0
  getTopics();
}

function fetchForum(id) {
  for (let type of store.state.forum.types) {
    if (type.id === id) {
      return type;
    }
  }
}
</script>

<style scoped>
.list-collect-button {
                    font-size: 14px;
                    display: flex;
                    justify-content: space-between;
                    transition:.3s;
  &:hover {
    cursor: pointer;
    opacity: 0.6;
  }
                  }


.action-container {
  display: flex;
  gap: 20px;
  font-size: 13px;
  margin-top: 10px;
  align-items: center;
  justify-content: flex-end;
}

.action-item {
  display: flex;
  align-items: center;
}

.icon {
  vertical-align: middle;
  margin-right: 5px;
}

.top-card{
  display: flex;
  div:first-of-type {
    margin-left: 10px;
    font-weight: bold;
    font-size: 14px;
    transition: color 0.2s;
    &:hover{
      color: grey;
    }
  }
  &:hover{
    cursor: pointer;
  }
  div:last-of-type {
    flex:1;
    text-align: right;
    font-size: 12px;
    color: grey;

  }

}
.type-select-card {
  background-color: #ffffff;
  border-radius: 3px;
  padding: 10px;
  box-sizing: border-box;
  transition: all 0.2s;
  &.active {
    border: 1px solid #000000;
  }
  &:hover {
    background-color: #f5f5f5;
    cursor: pointer;
    transform: scale(1.05);
  }
}

.topic-card {
  padding: 15px;
  font-size: 17px;
  &:hover {
    background-color: #efefef;
    cursor: pointer;
    transform: scale(1.02);
  }
  .topic-type {
    color: gray;
    font-size: 13px;
    margin-top: 5px;
  }
  .topic-content {
    color: gray;
    font-size: 13px;
    margin-top: 5px;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .topic-type {
    font-size: 12px;
    display: inline-block;
    border: 1px solid grey;
    border-radius: 5px;
    padding: 0 5px;
    margin-right: 7px;
  }
  .image-class {
    object-fit: cover;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    max-height: 120px;
  }
}

.info {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  margin: 10px 0;
  color: gray;
}

.friend-link {
  border-radius: 10px;
  background-color: #f5f5f5;
}

.create-topic {
  color: gray;
  align-items: center;
  border-radius: 5px;
  height: 40px;
  padding: 10px 15px;
  background-color: #efefef;
  font-size: 14px;
  &:hover {
    cursor: pointer;
  }
}

.fade-scale-enter-active,
.fade-scale-leave-active {
  transition: all 0.5s ease-out;
}
.fade-scale-enter-from,
.fade-scale-leave-to {
  transform: scale(0.9);
  opacity: 0;
}
.fade-scale-enter-to,
.fade-scale-leave-from {
  transform: scale(1);
  opacity: 1;
}

</style>
